package remote

import (
	"os"
	"sort"
	"sync"

	"gitee.com/dark.H/go-remote-repl/datas"
)

var (
	RegistedFunc = map[string]func(m *ApiServerMan){
		"1. sess": func(m *ApiServerMan) {
			m.SessionHandler()
		},
		"2. db in memory": func(m *ApiServerMan) {
			m.DbCli()
		},
		"3. file sync": func(m *ApiServerMan) {
			if raw_name, _ := m.FunctionInput("file sync", datas.G{
				"api":    "upload file and detect options for it, then chmod +x it, can be rpc call",
				"normal": "just upload as file",
			}); raw_name != "" {
				defer m.con.Close()
				m.RecvFileByRawName(raw_name)
			}
		},
	}
	locker = sync.Mutex{}
)

// type SortBy []string

// func (a SortBy) Len() int      { return len(a) }
// func (a SortBy) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// func (a SortBy) Less(i, j int) bool {
// 	one := a[i][0]
// 	two := a[j][0]

// 	return a[i] < a[j]
// }

// type Tui interface {
// 	Choose  func(pre string,ops ...string)

// }

func (m *ApiServerMan) IntoMenu() {
	serviceName := os.Args[0]
	names := []string{}
	sort.Strings(names)
	for k := range RegistedFunc {
		names = append(names, k)
	}

	if oper, err := m.Choose(serviceName+" service Menu", names...); err == nil {
		if handler, ok := RegistedFunc[oper]; ok {
			handler(m)
		}
	} else {
		datas.JsonErr(err, m.con)
		m.con.Close()
		return
	}

}

func RegistedService(name string, m func(m *ApiServerMan)) {
	locker.Lock()
	defer locker.Unlock()
	RegistedFunc[name] = m
}
